<template>
  <div class="login-wrap">
    <a-card title="登录" style="width:360px">
      <a-form :model="form" layout="vertical">
        <a-form-item field="username" label="用户名" required>
          <a-input v-model="form.username" placeholder="用户名" allow-clear />
        </a-form-item>
        <a-form-item field="password" label="密码" required>
          <a-input-password v-model="form.password" placeholder="密码" allow-clear />
        </a-form-item>
        <a-form-item field="captcha" label="验证码" required>
          <div style="display:flex;gap:8px;align-items:center;">
            <a-input v-model="form.captcha" placeholder="验证码" allow-clear style="flex:1;" />
            <img :src="captchaUrl" @click="refreshCaptcha" alt="验证码" style="height:32px;cursor:pointer;border-radius:4px;" />
          </div>
        </a-form-item>
        <a-form-item>
          <a-space direction="vertical" style="width:100%">
            <a-button type="primary" long :loading="loading" @click="onSubmit">登录</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '@/store/modules/auth';
import { BASE_URL } from '@/utils/request';

const router = useRouter();
const auth = useAuthStore();

const form = reactive({ username: '', password: '', captcha: '' });
const loading = ref(false);

const CAPTCHA_PATH = import.meta.env?.VITE_CAPTCHA_PATH || '/captcha/getCaptcha';
const captchaTs = ref(Date.now());
const captchaUrl = computed(() => `${BASE_URL}${CAPTCHA_PATH}?ts=${captchaTs.value}`);
function refreshCaptcha() { captchaTs.value = Date.now(); }

async function onSubmit() {
  if (!form.username || !form.password) return;
  loading.value = true;
  try {
    await auth.login({ ...form });
    router.replace('/');
  } catch (err) {
    refreshCaptcha();
  } finally {
    loading.value = false;
  }
}
</script>

<style scoped>
.login-wrap {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f6f7fb;
  padding: 24px;
}
</style>
